package org.jdk.learning.thread;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @author xin
 * @version 1.0
 */
public class CountDownLatchDemo {

    public static void main(String[] args ) {
        ExecutorService executorService = Executors.newFixedThreadPool(2);
        CountDownLatch latch = new CountDownLatch(2);
        executorService.execute(new Part1(latch));
        executorService.execute(new Part2(latch));

        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("finish main");

        executorService.shutdown();

        if(!executorService.isShutdown()) {
            executorService.shutdownNow();
        }

    }
}

class Part1 implements Runnable {

    private CountDownLatch latch;

    Part1(CountDownLatch latch) {
        this.latch = latch;
    }

    @Override
    public void run() {

        try {
            TimeUnit.SECONDS.sleep(5L);
            System.out.println("finish part1");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            latch.countDown();
        }
    }
}

class Part2 implements Runnable {

    private CountDownLatch latch;

    Part2(CountDownLatch latch) {
        this.latch = latch;
    }

    @Override
    public void run() {

        try {
            TimeUnit.SECONDS.sleep(5L);
            System.out.println("finish part2.");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            latch.countDown();
        }
    }
}
